package com.xjscrm.console.service.customer.group.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.group.MicaTriggerJoinGroupInviteMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.AcceptGroupInvite;
import com.xjscrm.common.entity.AccpetGroupInviteTask;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.common.enums.DeviceTypeEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.newcustmoerplan.SleepRule;
import com.xjscrm.common.vo.operatorplandevice.OperatorPlanDeviceRule;
import com.xjscrm.console.entity.MerchatChildDeviceRelation;
import com.xjscrm.console.mapper.AccpetGroupInviteTaskMapper;
import com.xjscrm.console.mapper.MerchatChildDeviceRelationMapper;
import com.xjscrm.console.mapper.WwDeviceMapper;
import com.xjscrm.console.mapper.WwGroupInviteMapper;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.group.*;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.customer.group.WwGroupInviteService;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import com.xjscrm.console.vo.AcceptGroupInviteVo;
import com.xjscrm.console.vo.AccpetGroupInviteTaskVo;
import com.xjscrm.console.vo.MyPageInfo;
import com.xjscrm.console.vo.WwDeviceVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class WwGroupInviteServiceImpl implements WwGroupInviteService {

    @Autowired
    private WwGroupInviteMapper wwGroupInviteMapper;

    @Autowired
    private WwDeviceService wwDeviceService;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private AccpetGroupInviteTaskMapper accpetGroupInviteTaskMapper;

    @Autowired
    private SendMsgProducer sendMsgProducer;

    @Autowired
    private MerchatChildDeviceRelationMapper merchatChildDeviceRelationMapper;
    @Override
    public void addAcceptGroupInvite(AcceptGroupInviteDto acceptGroupInviteDto) {
        if(acceptGroupInviteDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        //新增
        if(acceptGroupInviteDto.getId()==null){
            AcceptGroupInvite acceptGroupInvite=new AcceptGroupInvite();
            BeanUtil.copyProperties(acceptGroupInviteDto,acceptGroupInvite);
            acceptGroupInvite.setSleepRule(JSONObject.toJSONString(acceptGroupInviteDto.getRule()));
            wwGroupInviteMapper.add(acceptGroupInvite);
        }
        //修改
        if(acceptGroupInviteDto.getId()!=null){
           AcceptGroupInvite acceptGroupInvite= wwGroupInviteMapper.getById(acceptGroupInviteDto.getId(),acceptGroupInviteDto.getMerId());
           if(acceptGroupInvite==null){
               throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人接受群邀请配置未找到");
           }
            BeanUtil.copyProperties(acceptGroupInviteDto,acceptGroupInvite);
            acceptGroupInvite.setSleepRule(JSONObject.toJSONString(acceptGroupInviteDto.getRule()));
            wwGroupInviteMapper.update(acceptGroupInvite);
        }

    }

    @Override
    public Object getAccpetGroupInviteList(AcceptGroupInviteQuery acceptGroupInviteQuery) {
        if(acceptGroupInviteQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();

        //如果是子账号，只能查看自己账号所管理的 机器人
        if (acceptGroupInviteQuery.getOperatorType() != null && acceptGroupInviteQuery.getOperatorType() == 1) {
            if (acceptGroupInviteQuery.getChildId() == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID为空");
            }
            List<MerchatChildDeviceRelation> merchatChildDeviceRelationList = merchatChildDeviceRelationMapper.selectByStaffId(acceptGroupInviteQuery.getMerId(), acceptGroupInviteQuery.getChildId());
            if (merchatChildDeviceRelationList == null || merchatChildDeviceRelationList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> deviceUniqueIds = merchatChildDeviceRelationList.stream().map(MerchatChildDeviceRelation::getRobotId).distinct().collect(Collectors.toList());
            wwDeviceQuery.setChildOwnDeviceUniqueIds(deviceUniqueIds);
        }

        wwDeviceQuery.setCurrent(acceptGroupInviteQuery.getCurrent());
        wwDeviceQuery.setSize(acceptGroupInviteQuery.getSize());
        wwDeviceQuery.setOrderByField(acceptGroupInviteQuery.getOrderByField());
        wwDeviceQuery.setAsc(acceptGroupInviteQuery.isAsc());
        wwDeviceQuery.setMerId(acceptGroupInviteQuery.getMerId());
        if(!StringUtils.isBlank(acceptGroupInviteQuery.getKeyword())){
            wwDeviceQuery.setKeyword(acceptGroupInviteQuery.getKeyword());
        }
       if(acceptGroupInviteQuery.getGroupId()!=null){
           wwDeviceQuery.setGroupId(acceptGroupInviteQuery.getGroupId());
       }
        MyPageInfo<WwDeviceVo> wwDeviceVoMyPageInfo = wwDeviceService.getWwDevice(wwDeviceQuery);

       if(wwDeviceVoMyPageInfo.getRecords()==null||wwDeviceVoMyPageInfo.getRecords().isEmpty()){
           return new MyPageInfo<>(null);
       }

       List<AcceptGroupInviteVo> acceptGroupInviteVoList=new ArrayList<>();
        for (WwDeviceVo wwDeviceVo:wwDeviceVoMyPageInfo.getRecords()) {
            try {
                AcceptGroupInviteVo acceptGroupInviteVo=new AcceptGroupInviteVo();

              AcceptGroupInvite acceptGroupInvite=  wwGroupInviteMapper.getByDeviceUniqueId(wwDeviceVo.getId(),wwDeviceVo.getMerId());
              if(acceptGroupInvite!=null){
                  acceptGroupInviteVo.setId(acceptGroupInvite.getId());
                  acceptGroupInviteVo.setMerId(acceptGroupInvite.getMerId());
                  acceptGroupInviteVo.setDeviceUniqueId(acceptGroupInvite.getDeviceUniqueId());
                  acceptGroupInviteVo.setDeviceName(wwDeviceVo.getDeviceName());
                  acceptGroupInviteVo.setHeadImgUrl(wwDeviceVo.getHeadImgUrl());
                  acceptGroupInviteVo.setAutoAcceptInviteSwitch(acceptGroupInvite.getAutoAcceptInviteSwitch());
                  acceptGroupInviteVo.setAcceptToday(acceptGroupInvite.getAcceptToday());
                  acceptGroupInviteVo.setAcceptTotal(acceptGroupInvite.getAcceptTotal());
                  acceptGroupInviteVo.setMinGap(acceptGroupInvite.getMinGap());
                  acceptGroupInviteVo.setMaxGap(acceptGroupInvite.getMaxGap());
                  acceptGroupInviteVo.setRule(JSONObject.parseObject(acceptGroupInvite.getSleepRule(), OperatorPlanDeviceRule.class));
                  acceptGroupInviteVo.setCreateTime(acceptGroupInvite.getCreateTime());
                  acceptGroupInviteVo.setUpdateTime(acceptGroupInvite.getUpdateTime());
                  acceptGroupInviteVoList.add(acceptGroupInviteVo);
              }else {
                  acceptGroupInviteVo.setMerId(wwDeviceVo.getMerId());
                  acceptGroupInviteVo.setDeviceUniqueId(wwDeviceVo.getId());
                  acceptGroupInviteVo.setDeviceName(wwDeviceVo.getDeviceName());
                  acceptGroupInviteVo.setHeadImgUrl(wwDeviceVo.getHeadImgUrl());
                  acceptGroupInviteVo.setAutoAcceptInviteSwitch(0);
                  acceptGroupInviteVo.setAcceptToday(0);
                  acceptGroupInviteVo.setAcceptTotal(200);
                  acceptGroupInviteVo.setMinGap(5);
                  acceptGroupInviteVo.setMaxGap(10);
                  SleepRule sleepRule=new SleepRule();
                  sleepRule.setMinTime("22:00");
                  sleepRule.setMinTime("08:00");
                  List<SleepRule> sleepRuleList=new ArrayList<>();
                  sleepRuleList.add(sleepRule);
                  OperatorPlanDeviceRule operatorPlanDeviceRule=new OperatorPlanDeviceRule();
                  operatorPlanDeviceRule.setSleepSwitch(0);
                  operatorPlanDeviceRule.setSleepRules(sleepRuleList);
                  acceptGroupInviteVo.setRule(operatorPlanDeviceRule);
                  acceptGroupInviteVoList.add(acceptGroupInviteVo);
              }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        MyPageInfo<AcceptGroupInviteVo> acceptGroupInviteVoMyPageInfo = new MyPageInfo<>(acceptGroupInviteVoList);
        acceptGroupInviteVoMyPageInfo.setPages(wwDeviceVoMyPageInfo.getPages());
        acceptGroupInviteVoMyPageInfo.setSize(wwDeviceVoMyPageInfo.getSize());
        acceptGroupInviteVoMyPageInfo.setCurrent(wwDeviceVoMyPageInfo.getCurrent());
        acceptGroupInviteVoMyPageInfo.setTotal(wwDeviceVoMyPageInfo.getTotal());

        return acceptGroupInviteVoMyPageInfo;
    }


    @Override
    public void setAutoAcceptInviteSwitch(AutoAcceptInviteSwitchDto autoAcceptInviteSwitchDto) {
        if(autoAcceptInviteSwitchDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(autoAcceptInviteSwitchDto.getAutoAcceptInviteSwitch()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        //修改
        if(autoAcceptInviteSwitchDto.getId()!=null){
            AcceptGroupInvite acceptGroupInvite= wwGroupInviteMapper.getById(autoAcceptInviteSwitchDto.getId(),autoAcceptInviteSwitchDto.getMerId());
            if(acceptGroupInvite==null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人接受群邀请配置未找到");
            }
            acceptGroupInvite.setAutoAcceptInviteSwitch(autoAcceptInviteSwitchDto.getAutoAcceptInviteSwitch());
            wwGroupInviteMapper.update(acceptGroupInvite);
        }

        //新增
        if(autoAcceptInviteSwitchDto.getId()==null){
            if(autoAcceptInviteSwitchDto.getDeviceUniqueId()==null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新增必须传机器人ID");
            }
            AcceptGroupInvite acceptGroupInvite=new AcceptGroupInvite();
            acceptGroupInvite.setMerId(autoAcceptInviteSwitchDto.getMerId());
            acceptGroupInvite.setDeviceUniqueId(autoAcceptInviteSwitchDto.getDeviceUniqueId());
            acceptGroupInvite.setAutoAcceptInviteSwitch(autoAcceptInviteSwitchDto.getAutoAcceptInviteSwitch());
            acceptGroupInvite.setAcceptToday(0);
            acceptGroupInvite.setAcceptTotal(200);
            acceptGroupInvite.setMinGap(5);
            acceptGroupInvite.setMaxGap(10);
            SleepRule sleepRule=new SleepRule();
            sleepRule.setMinTime("22:00");
            sleepRule.setMinTime("08:00");
            List<SleepRule> sleepRuleList=new ArrayList<>();
            sleepRuleList.add(sleepRule);
            OperatorPlanDeviceRule operatorPlanDeviceRule=new OperatorPlanDeviceRule();
            operatorPlanDeviceRule.setSleepSwitch(0);
            operatorPlanDeviceRule.setSleepRules(sleepRuleList);
            acceptGroupInvite.setSleepRule(JSONObject.toJSONString(operatorPlanDeviceRule));
            wwGroupInviteMapper.add(acceptGroupInvite);
        }
    }

    @Override
    public void batchAddAcceptGroupInvite(AcceptGroupInviteDto acceptGroupInviteDto) {
        if(acceptGroupInviteDto.getBatchdeviceInfoList()==null&&acceptGroupInviteDto.getBatchdeviceInfoList().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        for (BatchdeviceInfo batchdeviceInfo:acceptGroupInviteDto.getBatchdeviceInfoList()) {
            try {
                if(batchdeviceInfo.getId()!=null){
                    acceptGroupInviteDto.setId(batchdeviceInfo.getId());
                }
                acceptGroupInviteDto.setDeviceUniqueId(batchdeviceInfo.getDeviceUniqueId());
                addAcceptGroupInvite(acceptGroupInviteDto);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


    @Override
    public void joinGroupInvite(JoinGroupInviteDto joinGroupInviteDto) {
          if(joinGroupInviteDto.getMerId()==null){
              return;
          }
        if(joinGroupInviteDto.getDeviceId()==null){
            return;
        }

        WwDevice wwDevice= wwDeviceMapper.getByDeviceId(joinGroupInviteDto.getDeviceId(),joinGroupInviteDto.getMerId());

        if(wwDevice==null){
            return;
        }

        //查看该机器人的接受群邀请的配置
        AcceptGroupInvite acceptGroupInvite = wwGroupInviteMapper.getByDeviceUniqueId(wwDevice.getId(), wwDevice.getMerId());
        if(acceptGroupInvite==null){
            return;
        }

        if(acceptGroupInvite.getAutoAcceptInviteSwitch()==null||acceptGroupInvite.getAutoAcceptInviteSwitch()==0){
            return;
        }

//        //获取今日成功执行的条数
//        Integer excutedNum= accpetGroupInviteTaskMapper.getTodayExcuted(joinGroupInviteDto.getMerId(),wwDevice.getId());
//        //如果不相同，则同步
//        if(excutedNum!=null&&!excutedNum.equals(acceptGroupInvite.getAcceptToday())){
//            acceptGroupInvite.setAcceptToday(excutedNum);
//            wwGroupInviteMapper.update(acceptGroupInvite);
//        }


        Integer earlyMorningTimestampAfterDays=0;
        //查看今日接受是否等于大于等于上限
        if(acceptGroupInvite.getAcceptToday()>=acceptGroupInvite.getAcceptTotal()){
            //查看未执行的条数
            Integer  num=  accpetGroupInviteTaskMapper.getNotExcute(joinGroupInviteDto.getMerId(),wwDevice.getId());
            if(num==0){
                earlyMorningTimestampAfterDays = Math.toIntExact(DateUtil.getEarlyMorningTimestampAfterDays(1));
            }else {
                if(num%acceptGroupInvite.getAcceptTotal()==0){
                    int result = (int) Math.ceil((double) num / acceptGroupInvite.getAcceptTotal());
                    earlyMorningTimestampAfterDays = Math.toIntExact(DateUtil.getEarlyMorningTimestampAfterDays(result));
                }
            }
        }

        //获取间隔后的执行时间
        Integer excuteTime=0;
        AccpetGroupInviteTask accpetGroupInviteTaskLastOne=  accpetGroupInviteTaskMapper.getLastOne(joinGroupInviteDto.getMerId(),wwDevice.getId());

        if(earlyMorningTimestampAfterDays!=0){
            excuteTime=earlyMorningTimestampAfterDays+getRandomTimeInterval(acceptGroupInvite.getMinGap(),acceptGroupInvite.getMaxGap());;
        }
        if(earlyMorningTimestampAfterDays==0&&accpetGroupInviteTaskLastOne==null){
            excuteTime=DateUtil.getTime()+getRandomTimeInterval(acceptGroupInvite.getMinGap(),acceptGroupInvite.getMaxGap());;
        }
        if(earlyMorningTimestampAfterDays==0&&accpetGroupInviteTaskLastOne!=null&&acceptGroupInvite.getAcceptToday()<=acceptGroupInvite.getAcceptTotal()){
            excuteTime=DateUtil.getTime()+getRandomTimeInterval(acceptGroupInvite.getMinGap(),acceptGroupInvite.getMaxGap());;
        }
        if(earlyMorningTimestampAfterDays==0&&accpetGroupInviteTaskLastOne!=null&&acceptGroupInvite.getAcceptToday()>acceptGroupInvite.getAcceptTotal()){
            excuteTime=accpetGroupInviteTaskLastOne.getExecuteTime()+getRandomTimeInterval(acceptGroupInvite.getMinGap(),acceptGroupInvite.getMaxGap());
        }

        //查看执行时间是否处于休眠时间
        int finalExcuteTime=0;
        OperatorPlanDeviceRule operatorPlanDeviceRule = JSONObject.parseObject(acceptGroupInvite.getSleepRule(), OperatorPlanDeviceRule.class);
        if(operatorPlanDeviceRule.getSleepSwitch()==1){
            List<SleepRule> sleepRules = operatorPlanDeviceRule.getSleepRules();
            for (SleepRule sleepRule:sleepRules) {
               if(isBetweenTimeRange(Long.valueOf(excuteTime), sleepRule.getMinTime(),sleepRule.getMaxTime())){
                   if(finalExcuteTime<Math.toIntExact(getTimestamp(sleepRule.getMinTime(), sleepRule.getMaxTime(), Long.valueOf(excuteTime)))){
                       finalExcuteTime = Math.toIntExact(getTimestamp(sleepRule.getMinTime(), sleepRule.getMaxTime(), Long.valueOf(excuteTime)));

                       AccpetGroupInviteTask accpetGroupInviteTask=accpetGroupInviteTaskMapper.getLastOneMaxTime(joinGroupInviteDto.getMerId(),wwDevice.getId(),finalExcuteTime);
                       if(accpetGroupInviteTask!=null){
                           finalExcuteTime=accpetGroupInviteTask.getExecuteTime()+getRandomTimeInterval(acceptGroupInvite.getMinGap(),acceptGroupInvite.getMaxGap());
                       }
                   }
               }
            }

        }else {
            finalExcuteTime=excuteTime;
        }


        AccpetGroupInviteTask accpetGroupInviteTask=new AccpetGroupInviteTask();
        accpetGroupInviteTask.setPlanId(acceptGroupInvite.getId());
        accpetGroupInviteTask.setMerId(joinGroupInviteDto.getMerId());
        accpetGroupInviteTask.setDeviceUniqueId(wwDevice.getId());
        accpetGroupInviteTask.setDeviceId(wwDevice.getDeviceId());
        accpetGroupInviteTask.setConversationId(joinGroupInviteDto.getConversationId());
        accpetGroupInviteTask.setInviteWxId(joinGroupInviteDto.getInviteWxId());
        accpetGroupInviteTask.setGroupInviteUrl(joinGroupInviteDto.getGroupInviteUrl());
        accpetGroupInviteTask.setExculted(0);
        accpetGroupInviteTask.setExecuteTime(finalExcuteTime);
        accpetGroupInviteTaskMapper.add(accpetGroupInviteTask);
    }


    @Override
    @Async("taskExecutor")
    public void clearAcceptToday(BaseDto baseDto) {
        AcceptGroupInviteQuery acceptGroupInviteQuery = new AcceptGroupInviteQuery();
        Long idStart = 0L;
        acceptGroupInviteQuery.setMerId(baseDto.getMerId());
        acceptGroupInviteQuery.setAsc(true);
        acceptGroupInviteQuery.setCurrent(1);
        acceptGroupInviteQuery.setSize(50);
        acceptGroupInviteQuery.setOrderByField("id");
        acceptGroupInviteQuery.setIdStart(idStart);
        String orderBy = OrderByUtil.getOrderBy(acceptGroupInviteQuery.getOrderByField(), acceptGroupInviteQuery.isAsc());
        PageHelper.startPage(acceptGroupInviteQuery.getCurrent(), acceptGroupInviteQuery.getSize(), orderBy);
        List<AcceptGroupInviteVo> acceptGroupInviteVoList = wwGroupInviteMapper.getAcceptGroupInviteList(acceptGroupInviteQuery);
        while (acceptGroupInviteVoList != null && !acceptGroupInviteVoList.isEmpty()) {
            for (AcceptGroupInviteVo acceptGroupInviteVo : acceptGroupInviteVoList) {
                try {
                    if (acceptGroupInviteVo.getId().longValue() > idStart.longValue()) {
                        idStart = acceptGroupInviteVo.getId();
                    }
                    AcceptGroupInvite acceptGroupInvite = new AcceptGroupInvite();
                    BeanUtil.copyProperties(acceptGroupInviteVo,acceptGroupInvite);
                    if(acceptGroupInvite.getAcceptToday()==0){
                        continue;
                    }
                    acceptGroupInvite.setAcceptToday(0);
                    wwGroupInviteMapper.update(acceptGroupInvite);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            acceptGroupInviteQuery.setIdStart(idStart);
            PageHelper.startPage(acceptGroupInviteQuery.getCurrent(), acceptGroupInviteQuery.getSize(), orderBy);
            acceptGroupInviteVoList = wwGroupInviteMapper.getAcceptGroupInviteList(acceptGroupInviteQuery);
        }
    }


    @Override
    @Async("taskExecutor")
    public void excuteTask(BaseDto baseDto) {
        AccpetGroupInviteTaskQuery accpetGroupInviteTaskQuery=new AccpetGroupInviteTaskQuery();
        Long idStart = 0L;
        accpetGroupInviteTaskQuery.setMerId(baseDto.getMerId());
        accpetGroupInviteTaskQuery.setAsc(true);
        accpetGroupInviteTaskQuery.setCurrent(1);
        accpetGroupInviteTaskQuery.setSize(50);
        accpetGroupInviteTaskQuery.setOrderByField("id");
        accpetGroupInviteTaskQuery.setIdStart(idStart);
        accpetGroupInviteTaskQuery.setExculted(0);
        accpetGroupInviteTaskQuery.setExecuteTime(DateUtil.getTime());
        String orderBy = OrderByUtil.getOrderBy(accpetGroupInviteTaskQuery.getOrderByField(), accpetGroupInviteTaskQuery.isAsc());
        PageHelper.startPage(accpetGroupInviteTaskQuery.getCurrent(), accpetGroupInviteTaskQuery.getSize(), orderBy);
        List<AccpetGroupInviteTaskVo> accpetGroupInviteTaskVoList = accpetGroupInviteTaskMapper.getAccpetGroupInviteTaskList(accpetGroupInviteTaskQuery);
        while (accpetGroupInviteTaskVoList != null && !accpetGroupInviteTaskVoList.isEmpty()) {
            for (AccpetGroupInviteTaskVo acceptGroupInviteTaskVo : accpetGroupInviteTaskVoList) {
                try {
                    if (acceptGroupInviteTaskVo.getId().longValue() > idStart.longValue()) {
                        idStart = acceptGroupInviteTaskVo.getId();
                    }

                    joinGroupInviteMsg(acceptGroupInviteTaskVo);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            accpetGroupInviteTaskQuery.setIdStart(idStart);
            PageHelper.startPage(accpetGroupInviteTaskQuery.getCurrent(), accpetGroupInviteTaskQuery.getSize(), orderBy);
            accpetGroupInviteTaskVoList = accpetGroupInviteTaskMapper.getAccpetGroupInviteTaskList(accpetGroupInviteTaskQuery);
        }

    }

    public void joinGroupInviteMsg(AccpetGroupInviteTaskVo acceptGroupInviteTaskVo) {


        AccpetGroupInviteTask accpetGroupInviteTask = new AccpetGroupInviteTask();
        BeanUtil.copyProperties(acceptGroupInviteTaskVo,accpetGroupInviteTask);
        //发送加入群邀请指令
        MicaTriggerJoinGroupInviteMsg micaTriggerJoinGroupInviteMsg=new MicaTriggerJoinGroupInviteMsg();
        micaTriggerJoinGroupInviteMsg.setMessageId(accpetGroupInviteTask.getId());
        micaTriggerJoinGroupInviteMsg.setInviteWxId(acceptGroupInviteTaskVo.getInviteWxId());
        micaTriggerJoinGroupInviteMsg.setConversationId(acceptGroupInviteTaskVo.getConversationId());
        micaTriggerJoinGroupInviteMsg.setGroupInviteUrl(acceptGroupInviteTaskVo.getGroupInviteUrl());

        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerJoinGroupInviteMsg, MicaTriggerType.TRIGGER_JOIN_GROUP_INVITE);
        micaTriggerDto.setMerId(accpetGroupInviteTask.getMerId());
        micaTriggerDto.setDeviceId(accpetGroupInviteTask.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

       //修改任务
        accpetGroupInviteTask.setExculted(1);
        accpetGroupInviteTaskMapper.update(accpetGroupInviteTask);

        //需改执行
        AcceptGroupInvite acceptGroupInvite = wwGroupInviteMapper.getById(accpetGroupInviteTask.getPlanId(), accpetGroupInviteTask.getMerId());
        acceptGroupInvite.setAcceptToday(acceptGroupInvite.getAcceptToday()+1);
        wwGroupInviteMapper.update(acceptGroupInvite);
    }

    public Integer getRandomTimeInterval(Integer minGap, Integer maxGap){
        Random random = new Random();
        return random.nextInt(maxGap - minGap + 1) + minGap;
    }


    public  boolean isBetweenTimeRange(Long createTime,String startTime,String endTime) {
        Instant instant_groupCreateTime = Instant.ofEpochMilli(createTime * 1000L);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant_groupCreateTime, ZoneId.systemDefault());
        boolean withinTimeInterval_groupCreateTime = Tools.isWithinTimeInterval(localDateTime, LocalTime.parse(startTime), LocalTime.parse(endTime));
        return withinTimeInterval_groupCreateTime;
    }


    public Long getTimestamp(String startTime, String endTime, Long createTime){
        LocalTime start = LocalTime.parse(startTime);
        LocalTime end = LocalTime.parse(endTime);

        if (end.isBefore(start)) {
            end = end.plusHours(24);
        }

        LocalDate today = LocalDate.now();
        LocalDate endDay = end.isBefore(start) ? today.plusDays(1) : today;

        LocalDate createDay = Instant.ofEpochSecond(createTime).atZone(ZoneId.systemDefault()).toLocalDate();

        int daysToAdd = (int) (createDay.toEpochDay() - today.toEpochDay());

        endDay = endDay.plusDays(daysToAdd);

        return end.atDate(endDay).atZone(ZoneId.systemDefault()).toEpochSecond();
    }

}
